/**
 * All rights Reserved, Designed By 林溪
 * Copyright:    Copyright(C) 2016-2020
 * Company       溪云阁 .
 */

package com.boots.shorturl.view.shorturl.view;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.boots.shorturl.common.utils.ShortUrlUtils;
import com.boots.shorturl.common.utils.UrlsUtils;
import com.module.boots.api.message.ResponseMsg;
import com.module.boots.api.utils.MsgUtils;
import com.module.boots.exception.CommonRuntimeException;
import com.module.boots.redis.RedisUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;

/**
 * 短链接服务
 * @author：溪云阁
 * @date：2020年6月11日
 */
@Api(tags = { "web服务：短链接服务接口" })
@RestController
@RequestMapping("view/shortUrl")
public class ShortUrlView {

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 生成短链接
     * @author 溪云阁
     * @param url 长连接地址
     * @return
     * @throws Exception ResponseMsg<String>
     */
    @ApiOperation(value = "生成短链接")
    @PostMapping(value = "/generateShortUrl")
    @SneakyThrows(CommonRuntimeException.class)
    public ResponseMsg<String> generateShortUrl(@RequestParam("url") String url) {
        // 判断是否为网址
        if (UrlsUtils.verifyUrl(url)) {
            // 生成6位数的随机短链接后缀,总共可以生成56800235584个
            final String suffix = ShortUrlUtils.getShortUr(6);
            // 生成完整的短链接
            final String shortUrl = UrlsUtils.getHost(url) + "/" + suffix;
            // 把短链接设置到Redis,这里为了方便,直接把短链接作为KEY,也可以把后缀作为key
            redisUtils.set(shortUrl, url);
            // 返回短链接地址
            return MsgUtils.buildSuccessMsg(shortUrl);

        } else {
            return MsgUtils.buildFailureMsg("网址不合法");
        }
    }

    /**
     * 获取长连接
     * @author 溪云阁
     * @param url
     * @return ResponseMsg<Object>
     */
    @ApiOperation(value = "获取长链接")
    @PostMapping(value = "/getLongUrl")
    @SneakyThrows(CommonRuntimeException.class)
    public ResponseMsg<Object> getLongUrl(@RequestParam("url") String url) {
        // 判断是否为网址
        if (UrlsUtils.verifyUrl(url)) {
            // 返回长链接地址
            return MsgUtils.buildSuccessMsg(redisUtils.get(url));

        } else {
            return MsgUtils.buildFailureMsg("网址不合法");
        }
    }

}
